'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports System.Windows.Forms
Imports System.Net

Public Class EFTel
    Public ISPReturnData As New ISPReturnData
    Private CookieContainer As New System.Net.CookieContainer

    Public Sub New(ByVal ConfigurationData As ConfigurationData)

        Try
            'set rollover date
            SetRolloverDate(ConfigurationData, ISPReturnData)

            Dim strHTMLData As String
            Dim strTemp As String = ""
            Dim Cost As String = ""
            Dim CostAvailable As Boolean = False

            'strHTMLData = My.Computer.FileSystem.ReadAllText("C:\programming\isp\eftel\limited\view_sessions.asp.htm", System.Text.Encoding.ASCII)

            'get login page to set cookies
            strTemp = ISPGet("https://myaccount.eftel.com/MyAccount/Security/SignOn.aspx", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            'extract VIEWSTATE
            Dim VIEWSTATE As String = EncodeHexString(ExtractText(strTemp, "__VIEWSTATE", 0, "value=""", """"))

            'login
            Dim POSTData As String = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" & VIEWSTATE & "&IdentifierTextBox=" & Replace(ConfigurationData.Username, "@", "%40") & "&PasswordTextBox=" & EncodeHexString(ConfigurationData.Password) & "&SignOnButton=Sign+on"
            strTemp = ISPPost("https://myaccount.eftel.com/MyAccount/Security/SignOn.aspx", POSTData, CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            If strTemp.Contains("issues concerning your internet account") = True Then
                ISPReturnData.ErrorMessage = "Login Failed"
                Exit Sub
            End If

            strHTMLData = ISPGet("https://myaccount.eftel.com/MyAccount/inquiry/view_sessions.asp", CookieContainer, System.Net.CredentialCache.DefaultCredentials, "https://myaccount.eftel.com/MyAccount/menu.asp")

            If UA.DebugISP = True Then My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug.htm", strHTMLData, False, System.Text.Encoding.ASCII)

            'logout
            ISPGet("https://myaccount.eftel.com/MyAccount/security/logout.asp?service_id=EFTEL", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            ISPReturnData.PeakUpload = CSng(Val(Replace(ExtractText(strHTMLData, ">Traffic</td>", 0, ">", "<"), ",", "")))
            ISPReturnData.PeakDownload = CSng(Val(Replace(ExtractText(strHTMLData, ">Traffic</td>", 40, ">", "<"), ",", "")))

            'check account type
            If strHTMLData.Contains("You are permitted unlimited traffic per month") = False Then
                'limited

                Dim Start As Integer
                Dim Finish As Integer

                Finish = InStr(strHTMLData, " MB of <i>peak</i> traffic per month.")
                Start = InStrRev(strHTMLData, " ", Finish - 1)

                'offpeak?
                If strHTMLData.Contains("Traffic off peak") = True Then
                    ISPReturnData.OffpeakUpload = CSng(Val(Replace(ExtractText(strHTMLData, ">Traffic off peak</td>", 0, ">", "<"), ",", "")))
                    ISPReturnData.OffpeakDownload = CSng(Val(Replace(ExtractText(strHTMLData, ">Traffic off peak</td>", 40, ">", "<"), ",", "")))

                    Finish = InStr(strHTMLData, " MB of <i>offpeak</i> traffic per month.")
                    Start = InStrRev(strHTMLData, " ", Finish - 1)
                End If

                'shaping?
                If strHTMLData.Contains("traffic is charged at") = True Then
                    CostAvailable = True
                    Dim TotalCost As Single
                    If ISPReturnData.PeakDownload > Val(ConfigurationData.PeakUsageLimit) Then
                        'calc peak cost
                        TotalCost = (ISPReturnData.PeakDownload - CSng(Val(ConfigurationData.PeakUsageLimit))) * CSng(Val(ConfigurationData.ExcessRate))
                    End If

                    Dim OffPeakCostPerMeg As Single = CSng(Val(ExtractText(strHTMLData, "Additional <i>offpeak</i> traffic is charged at $", 0, "", " ")))
                    If OffPeakCostPerMeg <> 0 Then
                        If ISPReturnData.OffpeakDownload > Val(ConfigurationData.OffpeakUsageLimit) Then
                            'calc offpeak cost
                            TotalCost += (ISPReturnData.OffpeakDownload - CSng(Val(ConfigurationData.OffpeakUsageLimit))) * CSng(Val(ConfigurationData.ExcessRate))
                        End If
                    End If
                    Cost = "$" & TotalCost
                End If
            End If

            'ISPReturnData.LastUpdated = CDate(ExtractText(strHTMLData, "Usage history for ", 0, "has been processed up to ", " ("))
            Dim LastUpdated As String = ExtractText(strHTMLData, "Usage history for ", 0, "has been processed up to ", " (")
            ISPReturnData.LastUpdated = Date.ParseExact(LastUpdated, "dd-MMM-yyyy HH:mm:ss", Nothing)

            '##########################################################

            ProcessISPData(ConfigurationData, ISPReturnData)

            'check for error
            If ISPReturnData.ErrorMessage <> "" Then Exit Sub

            '##########################################################

            'create graph data
            If ConfigurationData.PeakUnlimited = True Then
                'unlimited

                'downloads
                ISPReturnData.GraphItemList.Add(New GraphItem("Downloads " & ISPReturnData.PeakDownload & " (Unlimited)", ISPReturnData.PeakDownload, 0, False))

                'uploads
                ISPReturnData.GraphItemList.Add(New GraphItem("Uploads " & ISPReturnData.PeakUpload & " (Unlimited)", ISPReturnData.PeakUpload, 0, False))
            Else
                'limited

                'peak
                ISPReturnData.GraphItemList.Add(New GraphItem("Peak " & Format(System.Math.Floor((ISPReturnData.PeakDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload & " MB)", ISPReturnData.PeakDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), ISPReturnData.PeakNow))

                If ConfigurationData.OffpeakAvailable = True Then
                    'offpeak
                    ISPReturnData.GraphItemList.Add(New GraphItem("Offpeak " & Format(System.Math.Floor((ISPReturnData.OffpeakDownload / Val(ConfigurationData.OffpeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.OffpeakDownload & " MB)", ISPReturnData.OffpeakDownload, CSng(Val(ConfigurationData.OffpeakUsageLimit)), ISPReturnData.OffpeakNow))
                End If
            End If

            'days elapsed
            ISPReturnData.GraphItemList.Add(New GraphItem("Days Elapsed " & Format((ISPReturnData.DaysUsed / (ISPReturnData.DaysUsed + ISPReturnData.DaysLeft)) * 100, "#0") & "% (" & ISPReturnData.DaysUsed & " Days)", ISPReturnData.DaysUsed, ISPReturnData.DaysUsed + ISPReturnData.DaysLeft, False))

            '##########################################################

            'create stats data
            If ConfigurationData.PeakUnlimited = True Then
                ISPReturnData.TextItemList.Add(New TextItem("D/L Left :", ISPReturnData.PeakUsageRemainingDescription))
                ISPReturnData.TextItemList.Add(New TextItem("U/L Left :", ISPReturnData.PeakUsageRemainingDescription))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Peak Left :", ISPReturnData.PeakUsageRemainingDescription))
                ISPReturnData.TextItemList.Add(New TextItem("Peak Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))
                ISPReturnData.TextItemList.Add(New TextItem("Peak U/L:", ISPReturnData.PeakUpload & " MB"))
                If ConfigurationData.OffpeakAvailable = True Then
                    ISPReturnData.TextItemList.Add(New TextItem("Offpeak D/L Left :", ISPReturnData.OffpeakUsageRemainingDescription))
                    ISPReturnData.TextItemList.Add(New TextItem("Offpeak Avg. Left :", ISPReturnData.OffpeakUsageRemainingPerDayDescription))
                    ISPReturnData.TextItemList.Add(New TextItem("Offpeak U/L:", ISPReturnData.OffpeakUpload & " MB"))
                End If
                If ConfigurationData.PeakReached = "Shaped" Or ConfigurationData.OffpeakReached = "Shaped" Then
                    If ISPReturnData.ShapedNow = False Then
                        ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "NO"))
                    Else
                        ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "YES"))
                    End If
                End If
                If CostAvailable = True Then
                    ISPReturnData.TextItemList.Add(New TextItem("Excess Cost :", Cost))
                End If
            End If

            '##########################################################

            'process alerts
            ProcessAlerts(ConfigurationData, ISPReturnData)

        Catch ex As Exception
            ISPReturnData.ErrorMessage = ex.Message
        End Try
    End Sub

End Class
